<template>
  <AxiomDialog
    :model-value="visible"
    :title="title"
    width="500px"
    @close="handleClose"
    @cancel="handleClose"
    @confirm="handleConfirm"
    :confirm-loading="loading"
  >
    <AxiomForm :model="form" :rules="rules" ref="formRef" label-width="100px">
      <AxiomFormItem label="父级权限" prop="parent_id">
        <AxiomInput :model-value="parentName" disabled />
      </AxiomFormItem>
      <AxiomFormItem label="权限名称" prop="permission_name">
        <AxiomInput v-model="form.permission_name" placeholder="请输入权限名称" />
      </AxiomFormItem>
      <AxiomFormItem label="权限标识" prop="permission_code">
        <AxiomInput v-model="form.permission_code" placeholder="请输入权限标识" />
      </AxiomFormItem>
      <AxiomFormItem label="类型" prop="type">
        <AxiomSelect
          v-model="form.type"
          :options="permissionTypeOptions"
          placeholder="请选择权限类型"
          block
        />
      </AxiomFormItem>
       <AxiomFormItem label="图标" prop="icon">
        <AxiomIconPicker v-model="form.icon" />
      </AxiomFormItem>
      <AxiomFormItem label="排序" prop="sort">
        <AxiomInputNumber v-model="form.sort" :min="0" />
      </AxiomFormItem>
    </AxiomForm>
  </AxiomDialog>
</template>

<script setup>
import { ref, reactive, computed, watch, inject } from 'vue';
import {
  AxiomDialog,
  AxiomSelect,
  AxiomNumber,
  AxiomFormItem,
  AxiomInput,
  AxiomForm,
  AxiomIconPicker,
} from 'axiom-view';
import { createPermission, updatePermission } from '@/api/system/permission';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  mode: {
    type: String,
    default: 'add', // 'add' or 'edit'
  },
  initialData: {
    type: Object,
    default: () => ({}),
  },
  parentName: {
    type: String,
    default: '顶级权限',
  },
});

const emit = defineEmits(['close', 'success']);
const { notification } = inject('axiom-utils');
const formRef = ref(null);

const loading = ref(false);
const form = reactive({});

const rules = reactive({
  permission_name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
  permission_code: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
  type: [{ required: true, message: '请选择权限类型', trigger: 'change' }],
});

const permissionTypeOptions = ref([
  { label: '菜单', value: 'MENU' },
  { label: '按钮', value: 'BUTTON' },
  { label: '接口', value: 'API' },
]);

const title = computed(() => (props.mode === 'add' ? '新增权限' : '编辑权限'));

watch(() => props.visible, (val) => {
  if (val) {
    // [核心修复] 只从 initialData 中提取表单需要的字段，避免污染
    const cleanData = {
      parent_id: props.initialData.parent_id ?? '0',
      permission_name: props.initialData.permission_name ?? '',
      permission_code: props.initialData.permission_code ?? '',
      type: props.initialData.type ?? 'MENU',
      icon: props.initialData.icon ?? '',
      sort: props.initialData.sort ?? 0,
    };

    // 如果是编辑模式，还需要 id
    if (props.mode === 'edit' && props.initialData.id) {
      cleanData.id = props.initialData.id;
    }
    
    Object.assign(form, cleanData);

  } else {
    // 对话框关闭时，清理表单
     if (formRef.value) {
      formRef.value.resetFields();
    }
    // 手动清空响应式对象
    Object.keys(form).forEach(key => delete form[key]);
  }
});

const handleClose = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  emit('close');
};

const handleConfirm = async () => {
  try {
    if (!formRef.value) return;
    await formRef.value.validate();
    loading.value = true;

    const payload = { ...form };

    if (props.mode === 'add') {
      await createPermission(payload);
      notification.success({ title: '成功', message: '新增成功' });
    } else {
      await updatePermission(payload.id, payload);
      notification.success({ title: '成功', message: '更新成功' });
    }

    emit('success');
    handleClose();
  } catch (error) {
    console.error('表单提交失败:', error);
  } finally {
    loading.value = false;
  }
};
</script> 